package tw.cuttle.view.jsp;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import tw.cuttle.CuttleContext;
import tw.cuttle.bean.Action;
import tw.cuttle.bean.Process;
import tw.cuttle.handler.ProcessHandler;

/**
 * @author andy.chuang
 * 
 */
public class PageWrapTag extends BodyTagSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 3682690788219329700L;
    private static Log LOGGER = LogFactory.getLog(PageWrapTag.class);
    private String appendParameter;
    private String processId;

    /**
     * @return the processId
     */
    public String getProcessId() {
	return processId;
    }

    /**
     * @param processId
     *            the processId to set
     */
    public void setProcessId(String processId) {
	this.processId = processId;
    }

    /**
     * @return the appendParameter
     */
    public String getAppendParameter() {
	return appendParameter;
    }

    /**
     * @param appendParameter
     *            the appendParameter to set
     */
    public void setAppendParameter(String appendParameter) {
	this.appendParameter = appendParameter;
    }

    public int doStartTag() throws JspException {
	return EVAL_BODY_BUFFERED;
    }

    public int doAfterBody() throws JspException {
	return EVAL_BODY_INCLUDE;
    }

    public int doEndTag() throws JspException {
	try {
		
	    pageContext.getOut().print("<span id=\"" + processId + "\">");
	    Action currentAction = CuttleContext.getActionContext().getActionHelper().getCurrentAction();
	    JspCacheManager jspCacheManager = CuttleContext.getProcessContext().getJspCacheManager();
	    Process process = CuttleContext.getBeanHolder().getProcess(currentAction.getId() + "-" + processId);

	    if (process == null) {
		LOGGER.error("Process id:" + processId + " not be set in Action:" + currentAction.getId());
	    }
	    if (jspCacheManager == null) {
		LOGGER.error("jspCacheManager must to be set in spring context!!");
	    }
	    ProcessHandler processHandler = new ProcessHandler();
	    String content = processHandler.evaluateView(process);
	    
	    writeContent(content);

	    pageContext.getOut().print("</span>");
	} catch (Exception e) {
		e.printStackTrace();
	    throw new RuntimeException(e);
	}
	return EVAL_PAGE;
    }

    private void writeContent(String content) throws Exception {
	
	pageContext.getOut().print(content);
    }

}
